import { createSlice } from '@reduxjs/toolkit'

const projectSlice = createSlice({
  name: 'project',
  initialState: {
    projects: [],
    curProject: null,
  },
  reducers: {
    setProjects: (state, action) => {
      state.projects = action.payload
    },
    addProject: (state, action) => {
      state.projects.push(action.payload)
    },
    removeProject: (state, action) => {
      state.projects = state.projects.filter(project => project.id !== action.payload)
    },
    setCurProject: (state, action) => {
      state.curProject = action.payload
      if (action.payload === null) {
        localStorage.removeItem('curProject')
      } else {
        localStorage.setItem('curProject', JSON.stringify(action.payload))
      }
    },
  },
})

export const { setProjects, addProject, removeProject, setCurProject } = projectSlice.actions

export const selectProjects = state => state.project.projects

export const selectCurProject = state => state.project.curProject

export default projectSlice.reducer
